package com.geovis.boot.service.config.web;

import com.geovis.boot.common.dto.Result;
import com.geovis.boot.common.exception.HatchException;
import com.geovis.boot.common.exception.SeataException;
import com.geovis.boot.common.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author cl
 */
@Slf4j
@RestControllerAdvice
public class RestCtrlExceptionHandler {

    @ExceptionHandler(HatchException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleHatchException(HatchException e) {

        String errorMsg = "Hatch exception";
        if (e!=null){
            errorMsg = e.getMsg();
            log.error(e.toString(), e);
        }
        return new ResultUtil<>().setErrorMsg(500, errorMsg);
    }

    @ExceptionHandler(SeataException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleSeataException(SeataException e) {
        log.error(e.getMsg());
        throw new RuntimeException("全局事务回滚");
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleException(Exception e) {

        String errorMsg = "Exception";
        if (e!=null){
            errorMsg = e.getMessage() == null ? e.toString() : e.getMessage();
            log.error(e.toString(), e);
        }
        return new ResultUtil<>().setErrorMsg(500, errorMsg);
    }
}
